<?php

namespace app\admin\controller\basic;

use app\common\controller\Backend;
use think\Db;

/**
 * 学校列表
 */
class Homeworkassignment extends Backend
{

    /**
     * @var \app\common\model\Homeworkassignment
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\Homeworkassignment;
        $ruleList = Db::name("teacher")->select();
        // 如果查询结果为空，赋值为空数组
        $this->rulelist = is_array($ruleList) ? $ruleList : [];
        $ruledata = [0 => __('None')];
        foreach ($this->rulelist as $k => &$v) {
            $ruledata[$v['id']] = $v['name'];
        }
        $this->view->assign('ruledata', $ruledata);
    }

    /**
     * 查看
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            $params = $this->request->param();

            // 查询主数据（带分页）
            $list = $this->model
                ->with('user')
                ->order($params['sort'] ?? 'id', $params['order'] ?? 'desc')
                ->paginate([
                    'list_rows' => $params['limit'] ?? 10,
                    'page'      => ($params['offset'] / $params['limit'] + 1) ?? 1
                ]);

            // 预加载数据
            $assignmentIds = array_column($list->items(), 'id');
            $teacherIds = array_unique(array_column($list->items(), 'teacher_id'));

            // 批量查询提交计数
            $submitCounts = Db::name('homework_assignment_relation')
                ->where('assignment_id', 'in', $assignmentIds)
                ->group('assignment_id')
                ->column('COUNT(*) as count', 'assignment_id');

            // 批量查询老师关联的班级
            $teacherClasses = Db::name('teacher_classes_relation')
                ->where('teacher_id', 'in', $teacherIds)
                ->select();
            $teacherClassesMap = [];
            foreach ($teacherClasses as $item) {
                $teacherClassesMap[$item['teacher_id']][] = $item['classes_id'];
            }

            $allClassIds = array_merge(...array_values($teacherClassesMap));
            $classStudentCounts = [];
            if (!empty($allClassIds)) {
                $classStudentCounts = Db::name('student_classes_relation')
                    ->where('classes_id', 'in', $allClassIds)
                    ->group('classes_id')
                    ->column('COUNT(DISTINCT student_id) as count', 'classes_id');
            }

            // 批量查询教师名称
            $teachers = Db::name('user')
                ->where('id', 'in', $teacherIds)
                ->column('username', 'id');

            // 处理数据
            foreach ($list as $key => $value) {
                $list[$key]['submit_count'] = $submitCounts[$value['id']] ?? 0;
                
                // 计算学生总数（去重）
                $studentCount = 0;
                if (!empty($teacherClassesMap[$value['teacher_id']])) {
                    foreach ($teacherClassesMap[$value['teacher_id']] as $classId) {
                        $studentCount += $classStudentCounts[$classId] ?? 0;
                    }
                }
                
                $list[$key]['total'] = $studentCount;
                $list[$key]['submit_rate'] = $studentCount > 0 
                    ? round(($list[$key]['submit_count'] / $studentCount) * 100, 2) . '%' 
                    : '0%';
                
                $list[$key]['teacher_name'] = $teachers[$value['teacher_id']] ?? '';
            }
            $result = [
                "total" => $list->total(),
                "rows"  => $list->items()
            ];

            return json($result);
        }

        return $this->view->fetch();
    }
}